package com.winchannel.vitamin.modules.modeler.services;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BaseElement;
import org.flowable.bpmn.model.CustomProperty;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.editor.language.json.converter.BaseBpmnJsonConverter;
import org.flowable.editor.language.json.converter.UserTaskJsonConverter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class EXCustomizeUserTaskJsonConverter extends UserTaskJsonConverter {

    private static final String KEY_1 = "key11";
    private static final String KEY_2 = "key22";

    public static void fillBpmnTypes(Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap) {
        convertersToJsonMap.put(UserTask.class, EXCustomizeUserTaskJsonConverter.class);
    }

    @Override
    protected FlowElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, Map shapeMap) {
        FlowElement flowElement = super.convertJsonToElement(elementNode, modelNode, shapeMap);
        UserTask userTask = null;
        log.info("进入自定义属性解析");
        if (flowElement instanceof UserTask) {
            List<CustomProperty> customProperties = new ArrayList<>();
            userTask = (UserTask) flowElement;
            try {
                log.info("节点:" + objectMapper.writeValueAsString(userTask));
            } catch (JsonProcessingException e) {
                log.error("节点序列化异常.");
            }
            String value1 = getPropertyValueAsString(KEY_1, elementNode);
            String value2 = getPropertyValueAsString(KEY_2, elementNode);
            log.info("新增自定义属性[" + KEY_1 + "]=" + value1);
            log.info("新增自定义属性[" + KEY_2 + "]=" + value2);
            CustomProperty property1 = createProperty(KEY_1, value1);
            CustomProperty property2 = createProperty(KEY_2, value2);
            customProperties.add(property1);
            customProperties.add(property2);
            userTask.setCustomProperties(customProperties);
        }
        return userTask;
    }

    /**
     * 创建自定义属性
     *
     * @param propertyName  属性名称
     * @param propertyValue 属性值
     */
    private CustomProperty createProperty(String propertyName, String propertyValue) {
        CustomProperty customProperty = new CustomProperty();
        customProperty.setId(propertyName);
        customProperty.setName(propertyName);
        customProperty.setSimpleValue(propertyValue);
        return customProperty;
    }
}